<?php

	// +----------------------------------------------------------------------
	// | 邮件订阅管理
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\ucenter\admin;

	use app\controller\admin\Common;
	use app\model\ucenter\EmailHistory as EmailHistoryModel;
	use app\model\ucenter\Email as EmailModel;
	use app\event\ucenter\Email as EmailEvent;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;

	class Email extends Common
	{

		public function _filter()
		{
			$map = [];
			$map[] = ['status', '>', -2];
			return $map;
		}

		public function index()
		{
			// 显示页面
			$builder = new Table();
			$builder->title('订阅地址管理')
				->suggest('取消订阅的邮箱再次恢复需要谨慎')
				->model(EmailModel::class)
				->where($this->_filter())
				->order('id DESC')
				->searchText('address', '邮箱')
				->keyId()
				->keyText('address', '地址')
				->keyText('send_count', '发送次数')
				->keyBool('is_subscribe', '是否订阅')
				->keyText('reason', '自选原因')
				->keyText('other_reason', '其他原因')
				->keyCreateTime()
				//field[address]
                ->actionLink('ucenter/admin/EmailHistory/index?email_id={$id}', '记录')
				->actionUpdate();

			return $builder->fetch();
		}

		public function update()
		{
			if ($this->request->isPost()) {
				// 数据验证
				$result = $this->validate($this->request->post(), '\app\validate\ucenter\Email.edit');
				if ($result !== true) {
					$this->_returnError( '据验证错误，【' . $result . '】');
				} else {
					$event = new EmailEvent();
					$result = $event->update($this->request->post(), $this->user);
					if (0 == $result['code']) {
						$this->_returnSuccess( '操作成功', true);
					} else {
						$this->_returnError( '操作失败，失败信息【' . $result['message'] . '】');
					}
				}
			} else {
				$data = EmailModel::where('id', $this->request->param('id'))->find();
				if (!$data) {
					$this->_returnError( '需要修改的邮件不存在');
				}

				$builder = new Edit();
				$builder->title('编辑邮件')
					->keyTextInline('address', '邮件地址')
					->keyBool('is_subscribe', '订阅')
					->keyTextArea('other_reason', '填写原因', '')
					->explain('用户拒绝订阅之后请勿随意恢复')
					->data($data)
					->buttonSubmit();

				return $builder->fetch();
			}
		}
	}
